#include "../ui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdbool.h>

static lv_timer_t *battery_info_timer;

static bool btn_pressed = false; // 用于跟踪按钮状态

// 定时器回调函数，用于重置按钮状态
static void reset_btn_pressed(lv_timer_t *timer)
{
	btn_pressed = false; // 重置按钮状态
	lv_timer_del(timer); // 删除定时器
}

static void event_handler(lv_event_t * e)
{
    lv_obj_t * obj = lv_event_get_target(e);
    LV_LOG_USER("Button %d clicked", (int)lv_obj_get_index(obj));
}


static void net_update_time() 
{
    char buffer[128];
    FILE *fp = popen("wget -qO- http://worldtimeapi.org/api/timezone/Asia/Shanghai |\
		 awk -F'\"datetime\":\"' '{print $2}' | awk -F'.' '{print $1}'", "r");
		if (fp == NULL) {
        perror("popen failed");
        return;
    }

		printf("start to get nettime\n");

    if (fgets(buffer, sizeof(buffer), fp) != NULL) {
        // 格式化时间输出
				char *pos = strchr(buffer, 'T');
        if (pos != NULL) {
            *pos = ' ';
        }
				//更新系统时间
        char system_time_command[64];
        snprintf(system_time_command, sizeof(system_time_command), "date -s \"%s\"", buffer);
        system(system_time_command);
				system("hwclock --systohc");

        // 提示
				char settime_mesg[64];
        snprintf(settime_mesg, sizeof(settime_mesg), "Systime has been set:\n %s", buffer);
				info_msgbox(settime_mesg,"Time Info");
				printf("%s",settime_mesg);
    } else {
				info_msgbox("Failed to get time","Error");
    }

    pclose(fp);
}


////////////////////////
#define BUFFER_SIZE 256

static void read_wifi_status(WifiStatus *status) 
{
    char buffer[BUFFER_SIZE];
    FILE *fp = popen("wpa_cli status", "r");
    if (fp == NULL) 
		{
        perror("popen failed");
        return;
    }

    while (fgets(buffer, sizeof(buffer), fp) != NULL)
		 {
        if (strncmp(buffer, "bssid=", 6) == 0) {
            sscanf(buffer + 6, "%31s", status->bssid);
        } else if (strncmp(buffer, "freq=", 5) == 0) {
            sscanf(buffer + 5, "%d", &status->freq);
        } else if (strncmp(buffer, "ssid=", 5) == 0) {
            sscanf(buffer + 5, "%31s", status->ssid);
        } else if (strncmp(buffer, "id=", 3) == 0) {
            sscanf(buffer + 3, "%d", &status->id);
        } else if (strncmp(buffer, "mode=", 5) == 0) {
            sscanf(buffer + 5, "%31s", status->mode);
        } else if (strncmp(buffer, "wifi_generation=", 16) == 0) {
            sscanf(buffer + 16, "%d", &status->wifi_generation);
        } else if (strncmp(buffer, "pairwise_cipher=", 16) == 0) {
            sscanf(buffer + 16, "%31s", status->pairwise_cipher);
        } else if (strncmp(buffer, "group_cipher=", 13) == 0) {
            sscanf(buffer + 13, "%31s", status->group_cipher);
        } else if (strncmp(buffer, "key_mgmt=", 9) == 0) {
            sscanf(buffer + 9, "%31s", status->key_mgmt);
        } else if (strncmp(buffer, "wpa_state=", 10) == 0) {
            sscanf(buffer + 10, "%31s", status->wpa_state);
        } else if (strncmp(buffer, "ip_address=", 11) == 0) {
            sscanf(buffer + 11, "%31s", status->ip_address);
        } else if (strncmp(buffer, "address=", 8) == 0) {
            sscanf(buffer + 8, "%31s", status->address);
        }
    }

    pclose(fp);
}

void print_wifi_status(const WifiStatus *status) 
{
    printf("BSSID: %s\n", status->bssid);
    printf("Frequency: %d\n", status->freq);
    printf("SSID: %s\n", status->ssid);
    printf("ID: %d\n", status->id);
    printf("Mode: %s\n", status->mode);
    printf("WiFi Generation: %d\n", status->wifi_generation);
    printf("Pairwise Cipher: %s\n", status->pairwise_cipher);
    printf("Group Cipher: %s\n", status->group_cipher);
    printf("Key Management: %s\n", status->key_mgmt);
    printf("WPA State: %s\n", status->wpa_state);
    printf("IP Address: %s\n", status->ip_address);
    printf("Address: %s\n", status->address);

		char wifi_info_mesg[264];
		snprintf(wifi_info_mesg, sizeof(wifi_info_mesg), "State: %s\nSSID: %s\nIP: %s\n", \
										 status->wpa_state,status->ssid, status->ip_address);
		info_msgbox(wifi_info_mesg,"WiFi Info");
}
////////////////////////

static void mouse_test()
{
  lv_indev_t* indev = lv_indev_get_act(); //获取输入设备

  if (indev == NULL)  return;

  lv_point_t   lv_point;

  lv_indev_get_point(indev, &lv_point);

  printf("[%s]  lv_point.x = %d  lv_point.y = %d \n", __func__, lv_point.x, lv_point.y);
} 

static void btn_event_cb(lv_event_t *e)
{
	lv_event_code_t code = lv_event_get_code(e);
	lv_obj_t *btn = lv_event_get_target(e);
	uint32_t id = lv_btnmatrix_get_selected_btn(btn);
	if (code == LV_EVENT_VALUE_CHANGED)
	{
		if (!btn_pressed) // 检查按钮是否已经被按下
		{
			btn_pressed = true; // 标记按钮已被按下
			const char *btn_text = lv_btnmatrix_get_btn_text(btn, lv_btnmatrix_get_selected_btn(btn));

			if (strcmp(btn_text, "返回") == 0) /* 切换到功能1界面 */
			{
				lv_timer_del(battery_info_timer);
				ui_Home_screen_init();
				lv_scr_load_anim(ui_Home, LV_SCR_LOAD_ANIM_FADE_ON, 200, 0, true);
			}
			else if (strcmp(btn_text, "About") == 0) /* 切换到功能1界面 */
			{
				info_msgbox("\nBuild by JunGang\
				\n                       \n                       2024.8.1","About");
				 
			}
			else if (strcmp(btn_text, "Time") == 0) /* 切换到功能1界面 */
			{
				if(get_wifi_state())
				{
					pthread_t nettime_thread;
					pthread_create(&nettime_thread, NULL, net_update_time, NULL);
					pthread_detach(&nettime_thread);
					
				}
				else
				{
					info_msgbox("\nWiFi is disconnected","Error");
				}
				
			}
			
			else if (strcmp(btn_text, "WiFi") == 0) /* 切换到功能1界面 */
			{
				WifiStatus status = {0};
				read_wifi_status(&status);
				print_wifi_status(&status);
			}


			lv_timer_create(reset_btn_pressed, 100, NULL);
		}
	}
}



static void read_battery_info(lv_timer_t *timer)
{
	uint32_t *user_data = timer->user_data;

	FILE *file;
	int capacity, current_now, voltage_now, temp;
	char status[32], health[32];

	// Read battery capacity
	file = fopen("/sys/class/power_supply/battery/capacity", "r");
	if (file == NULL)
	{
		perror("Failed to open capacity file");
		return;
	}
	fscanf(file, "%d", &capacity);
	fclose(file);

	// // Read current now
	file = fopen("/sys/class/power_supply/battery/current_now", "r");
	if (file == NULL)
	{
		perror("Failed to open current_now file");
		return;
	}
	fscanf(file, "%d", &current_now);
	fclose(file);

	// Read voltage now
	file = fopen("/sys/class/power_supply/battery/voltage_now", "r");
	if (file == NULL)
	{
		perror("Failed to open voltage_now file");
		return;
	}
	fscanf(file, "%d", &voltage_now);
	fclose(file);

	// Read temperature
	file = fopen("/sys/class/power_supply/battery/temp", "r");
	if (file == NULL)
	{
		perror("Failed to open temp file");
		return;
	}
	fscanf(file, "%d", &temp);
	fclose(file);

	// Read battery status
	file = fopen("/sys/class/power_supply/battery/status", "r");
	if (file == NULL)
	{
		perror("Failed to open status file");
		return;
	}
	fscanf(file, "%s", status);
	fclose(file);

	// Read battery health
	file = fopen("/sys/class/power_supply/battery/health", "r");
	if (file == NULL)
	{
		perror("Failed to open health file");
		return;
	}
	fscanf(file, "%s", health);
	fclose(file);

	// Update LVGL labels
	lv_label_set_text_fmt(user_data, "battery:%d %% \nCurrent: %d mA  \nVoltage: %d mV \nTemperature: %d °C\nStatus: %s \nHealth: %s",
												capacity, current_now / 1000, voltage_now / 1000, temp / 10, status, health);
}

extern unsigned int back_ground_value;

static void create_function_widgets(lv_obj_t *parent)
{
	// 设置背景颜色
	// lv_obj_set_style_bg_color(parent, lv_color_hex(0x2c3e50), 0); // 现代化配色
	lv_obj_set_style_bg_color(parent, lv_color_hex(back_ground_value), 0);

	// 创建底部按钮
	static const char *btn_map[] = {"About","Time","WiFi", "返回", ""};
	lv_obj_t *btnm = lv_btnmatrix_create(parent);
	lv_btnmatrix_set_map(btnm, btn_map);
	lv_obj_set_size(btnm, lv_pct(90), lv_pct(25));
	lv_obj_align(btnm, LV_ALIGN_BOTTOM_MID, 0, -40);
	lv_obj_add_event_cb(btnm, btn_event_cb, LV_EVENT_ALL, NULL);

	// 设置按钮样式
	lv_obj_set_style_text_font(btnm, &lv_font_simsun_16_cjk, 0);
	// lv_obj_set_style_bg_color(btnm, lv_color_hex(0x34495e), LV_PART_MAIN);
	lv_obj_set_style_bg_color(btnm, lv_color_hex(0xDBDBDB), LV_PART_MAIN);
	lv_obj_set_style_border_width(btnm, 0, LV_PART_MAIN);
	lv_obj_set_style_radius(btnm, 10, LV_PART_MAIN);
	lv_obj_set_style_text_color(btnm, lv_color_hex(0xecf0f1), LV_PART_ITEMS);
	lv_obj_set_style_bg_color(btnm, lv_color_hex(0x3498db), LV_PART_ITEMS);
	lv_obj_set_style_radius(btnm, 5, LV_PART_ITEMS);

	// lv_btnmatrix_set_btn_ctrl_all(btnm, LV_BTNMATRIX_CTRL_CHECKABLE); // 设置所有按钮为可选中状态
	// lv_btnmatrix_set_one_checked(btnm, true);													// 设置按钮矩阵为一次只允许选中一个按钮

	lv_obj_t *battery_status_label;
	battery_status_label = lv_label_create(parent);
	lv_obj_set_style_text_font(battery_status_label, &lv_font_montserrat_16, 0);
	lv_obj_align(battery_status_label, LV_ALIGN_CENTER, 0, -45);

	battery_info_timer = lv_timer_create(read_battery_info, 200, battery_status_label);
	lv_timer_ready(battery_info_timer);
}

void ui_Screen2_screen_init(void)
{
	ui_Screen2 = lv_obj_create(NULL);
	lv_obj_clear_flag(ui_Screen2, LV_OBJ_FLAG_SCROLLABLE); /// Flags
	create_function_widgets(ui_Screen2);
}
